﻿using AduSkin.Controls.Metro;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.SQLite;
using Newtonsoft.Json;
using System.Configuration;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Common;
using System.Data;
using System.Text.RegularExpressions;

namespace HsServerHa.UserControls.Dialog
{
    /// <summary>
    /// AddProgram.xaml 的交互逻辑
    /// </summary>
    public partial class UpdateProgram : UserControl
    {
        private long Id { get; set; }
        public UpdateProgram(long Id)
        {
            this.Id = Id;
            InitializeComponent();
            initData(Id);
        }
        ProgramManageEntity proFirst=new ProgramManageEntity();
        public  void initData(long Id)
        {
            //var dt= DbHelperSQLite.Query($"select * from ProgramManage where Id={Id}")?.Tables?[0]; 
            //List<ProgramManageEntity> list = DataHelpers.ConvertToModel<ProgramManageEntity>(dt);

            var list = SQLiteHelper.Table<ProgramManageEntity>().Where(x => x.Id == Id).ToList();
            proFirst = list.FirstOrDefault();
            if (proFirst==null)
            {
                AduMessageBoxs.Show("程序错误，稍后再试！");
                return;
            }
            ProgramName.Text=proFirst.ProgramName;
            Delayed.Text=proFirst.Delayed;
            StartupSeq.Text=proFirst.StartupSeq;
            Src.Text=proFirst.Src;
            IsEnable.SelectedIndex = proFirst.IsEnable == "是" ? 0 : 1;
        }

        private async  void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(ProgramName.Text))
            {
                AduMessageBoxs.Show("请输入程序名称");
                return;
            }
            if (string.IsNullOrEmpty(Src.Text))
            {
                AduMessageBoxs.Show("请选择运行程序名称");
                return;
            }
            else
            {
                if (!Src.Text.EndsWith(".exe"))
                {
                    Src.Text = "";
                    AduMessageBoxs.Show("请选择正确的程序");
                    return;
                }
            }

            if (string.IsNullOrEmpty(StartupSeq.Text))
            {
                AduMessageBoxs.Show("请填写启动顺序！");
                return;
            }
            if (string.IsNullOrEmpty(Delayed.Text))
            {
                AduMessageBoxs.Show("请填写延时时长！");
                return;
            }

            if (string.IsNullOrEmpty(IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
            {
                AduMessageBoxs.Show("请选择是否启用");
                return;
            }


            if (App.isMaster == null)
            {
                AduMessageBoxs.Show("程序配置有误，请初始化配置");
                return;
            }

            //查询绑定信息
            //var dtBind = DbHelperSQLite.Query("select  * from MasterSlaveBind")?.Tables?[0];
            //var bindList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtBind);
            var bindList =  SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
            var bindFirst = bindList?.FirstOrDefault();
            if (bindFirst == null)
            {
                AduMessageBoxs.Show("程序配置有误，请初始化配置");
                return;
            }

            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定设置吗？", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK) {
                var parms = new ProgramManageEntity
                {
                    ProgramKey= proFirst.ProgramKey,
                    ProgramName = ProgramName.Text,
                    Src = Src.Text,
                    Delayed= Delayed.Text,
                    StartupSeq = StartupSeq.Text,
                    IsEnable = IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", ""),
                    CreateTime = DateTime.Now.ToString()
                };
                var result = new HttpResponseResultModel<object>();
                if (App.isMaster.Value)
                {
                    var slavePath = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    var getFilesExits = await HttpHelpers.Get<HttpResponseResultModel<object>>(slavePath + (ConfigurationManager.AppSettings["getFilesExits"]?.ToString() ?? "getFilesExits") + "?fileStr=" + Src.Text);
                    if (getFilesExits == null)
                    {
                        AduMessageBoxs.Show("从机不在线，请检查");
                        LoggerHelper.SetInfo("修改失败->从机不在线，请检查", "启动程序管理");
                        return;
                    }
                    if (!getFilesExits.IsSuccess)
                    {
                        AduMessageBoxs.Show("从机不存在该程序，请检查");
                        LoggerHelper.SetInfo("修改失败->从机不存在该程序，请检查", "启动程序管理");
                        return;
                    }
                    #region 上传程序数据给从机
              
                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
                   (ConfigurationManager.AppSettings["postUpdateProgram"]?.ToString() ?? "postUpdateProgram"), JsonConvert.SerializeObject(parms));

                    #endregion
                }
                else
                {
                    var masterPath = $"http://{App.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    var getFilesExits = await HttpHelpers.Get<HttpResponseResultModel<object>>(masterPath + (ConfigurationManager.AppSettings["getFilesExits"]?.ToString() ?? "getFilesExits") + "?fileStr=" + Src.Text);
                    if (getFilesExits == null)
                    {
                        AduMessageBoxs.Show("主机不在线，请检查");
                        LoggerHelper.SetInfo("修改失败->主机不在线，请检查", "启动程序管理");
                        return;
                    }
                    if (!getFilesExits.IsSuccess)
                    {
                        AduMessageBoxs.Show("主机不存在该程序，请检查");
                        LoggerHelper.SetInfo("修改失败->主机不存在该程序，请检查", "启动程序管理");
                        return;
                    }
                    #region 上传程序数据给主机
               
                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(masterPath +
                        (ConfigurationManager.AppSettings["postUpdateProgram"]?.ToString() ?? "postUpdateProgram"), JsonConvert.SerializeObject(parms));
                    #endregion
                }
                if (result == null)
                {
                    AduMessageBoxs.Show("修改失败");
                    LoggerHelper.SetInfo("修改失败->接口有误", "启动程序管理");
                    return;
                }
                else
                {
                    if (result.IsSuccess)
                    {
                        SQLiteHelper.ExecuteSql($"update ProgramManage set ProgramName='{ProgramName.Text}',Src='{Src.Text}',StartupSeq='{StartupSeq.Text}',Delayed='{Delayed.Text}',IsEnable='{IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")}' where ProgramKey='{proFirst.ProgramKey}'");

                        AduMessageBoxs.Show("修改成功！");
                        WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("刷新程序数据"), "RefreshProgram");
                        LoggerHelper.SetInfo("修改程序数据:" + JsonConvert.SerializeObject(parms), "启动程序管理");
                    }
                    else
                    {
                        AduMessageBoxs.Show("修改失败");
                        LoggerHelper.SetInfo("修改失败->接口返回false", "启动程序管理");
                        return;
                    }
                }
            }
            var control = this.Parent as ContentControl;
            Window win = Window.GetWindow(control);
            var title = win?.Title;
            if (title != null)
            {
                if (title != "HsServerHa")
                {
                    win.Close();
                }

            }
        }

        private void StartupSeq_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Regex.IsMatch(e.Text,"^[0-9]+$"))
            {
                e.Handled = true;
            }
        }
    }
}
